/* owatch
 *
 * Run each time your shell displays a prompt, emulating shell 'watch'
 * facilities.
 *
 * Allows you to receive messages when contacts login, logout, change status,
 * etc.
 *
 * Copyright 2009 Cian Synnott.
 * 
 *$Id: owatch.c 28 2009-12-04 03:01:17Z cian $
 */
#include <errno.h>
#include <getopt.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "log.h"
#include "utility.h"
#include "version.h"

static struct option longopts[] = {
  { "debug", no_argument, 0, 'D' },
  { "help", no_argument, 0, 'h' },
  { "version", no_argument, 0, 'V' },
  { 0, 0, 0, 0 }
};

static char *shortopts = "DhV";

static void usage(void) {
  puts("Usage: owatch [OPTIONS]\n"
    "Watches contact status changes for 'ohai', "
    "the jabber/xmpp commandline suite.\n"
    " -d, --debug        Be verbose in logging.\n"
    " -h, --help         Print this text.\n"
    " -V, --version      Print the version.\n"
    "See the project page at http://code.google.com/p/ohai/");
}

#define BUFSIZE 1024
int main(int argc, char *argv[]) {
  char buffer[BUFSIZE];
  int opt;
  int fd;
  FILE *fp;
  char *message;
  int quiet = 1;

  while ((opt = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) {
    switch(opt) {
      case 'D':
        log_set_debug();
        quiet = 0;
        break;
      case 'h':
        usage();
        exit(EXIT_SUCCESS);
        break;
      case 'V':
        puts("owatch " OHAI_VERSION);
        exit(EXIT_SUCCESS);
    }
  }

  /* Since owatch is designed to be run pre-prompt, let's be quiet about
   * exiting in connect_to_ohaigent by default. */
  fd = connect_to_ohaigent(quiet);

  socket_write(fd, "MESSAGES\n");

  if ((fp = fdopen(fd, "r")) == NULL)
    log_errx(EXIT_FAILURE, "Failed to open socket as an stdio FILE.");

  if (fgets(buffer, BUFSIZE, fp) == NULL)
    log_errx(EXIT_FAILURE, "Failed to get first line from socket.");

  log_debug("Received: |%s|", buffer);

  kill_newline(buffer);

  if (strcmp(buffer, "BEGIN"))
    log_errx(EXIT_FAILURE, "No BEGIN from server.");

  while (1) {
    if (fgets(buffer, BUFSIZE, fp) == NULL)
      log_errx(EXIT_FAILURE, "Failed to get line from socket.");
    log_debug("Received: |%s|", buffer);
    kill_newline(buffer);
    if (!strcmp(buffer, "END"))
      break;
    message = remainder_after_first_token(buffer);
    if (strcmp(buffer, "ITEM")) {
      log_err("Expected ITEM from server, got '%s'", buffer);
      continue;
    }
    puts(message);
  }

  if (fclose(fp) == EOF)
    log_errx(EXIT_FAILURE, "closing FILE stream for UNIX socket %d: %s", fd, strerror(errno));

  return 0;
}
